package net.wanderinghorse.jsonmessage;

import java.io.PrintStream;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *  A CallbackRequestOpt which simply logs its comings and goings to a Logger object.
 *  Intended only for testing and debugging.
 */
public class CallbackRequestOptToLogger implements CallbackRequestOpt {
    private Logger log;
    private String handlerName = null;
    private Level level;

    /**
     * Sets up this object to use the given logger.
     *
     * @param log The destination logger.
     * @param level The level at which all output is logged.
     * @param name A descriptive name for the callback object.
     */
    public CallbackRequestOptToLogger( final Logger log, final Level level, final String name ) {
        this.log = log;
        this.level = level;
        this.handlerName = name;
    }



    /**
     * A name to use for this object, primarily for debugging whether this is, e.g.
     * a beforePost() or afterPost() handler.
     * @param v The name string. May be null.
     * @return This object.
     */
    public CallbackRequestOptToLogger setName(String v) {
        this.handlerName = v;
        return this;
    }

    /**
     * Outputs the request and options to the stream passed in to the ctor,
     * in JSON format (but the output itself is not structured like a JSON
     * object, and cannot be used as-is back in as well-formed JSON).
     *
     * If an exception is thrown by r.toJSON() or o.toJSON() then an error
     * message is sent to the output stream.
     *
     * @param r The request which failed.
     * @param o The connection options used for the request.
     */
    public void invoke(Request r, PostOptions o) {
        log.log( level,
                getClass().getName()+"processResponse()[name="
                +this.handlerName
                +"]: "
        );
        try {
            int indent = JSONMessage.getDefaultIndentation();
            log.log( level,
                "Request = "
                +r.toJSON( indent )
                +"\nPostOptions = "+o.toJSON(indent)
            );
        }
        catch( Exception e ) {
            log.log( Level.SEVERE, "Exception in invoke() handler: "+e.toString(), e);
        }
    }

}
